package com.hong.record.common.util;

import com.hong.record.common.annotation.LogCompar;
import com.hong.record.common.util.entity.Record;
import org.apache.commons.beanutils.PropertyUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author hongji
 * @date 2019-12-06
 */
public class RecordUtil {

    public static <T> List<Record> getRecordList(T old, T update) throws IllegalAccessException {
        List<Record> list = new ArrayList<>();
        if (old == null || update == null){
            return list;
        }
        Field[] fields = update.getClass().getDeclaredFields();
        for (Field field:fields) {
            String name = field.getName();

            if (field.isAnnotationPresent(LogCompar.class)) {
                LogCompar anno = field.getAnnotation(LogCompar.class);
                //获取private对象字段值
                field.setAccessible(true);
                if (!field.get(old).equals(field.get(update))){
                    StringBuffer oldValue = new StringBuffer();
                    StringBuffer newValue = new StringBuffer();
                    if ("class java.util.Date".equals(field.getGenericType().toString())){
                        oldValue.append(getYYYYMMDDHHMMSS((Date) field.get(old),anno.dateFormat()));
                        newValue.append(getYYYYMMDDHHMMSS((Date) field.get(update),anno.dateFormat()));
                    }else {
                        System.out.println("====================");
                        System.out.println(field.getGenericType());
                        System.out.println(field.get(old));
                        System.out.println(field.get(update));
                        System.out.println("====================");
                        oldValue.append(field.get(old));
                        newValue.append(field.get(update));
                    }
                    Record record = Record.builder()
                            .alias(anno.name())
                            .field(name)
                            .oldValue(oldValue.toString())
                            .newValue(newValue.toString())
                            .build();
                    list.add(record);
                }
            }
        }
        return list;
    }

    public static String getYYYYMMDDHHMMSS(Date date,String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }
}
